<template>
  <div class="buttonGroupComponent" v-if="oItem">
    <div
      class="buttonSwiper"
      :class="
        oItem.main.carouselDotsPositionCls +
        ' ' +
        oItem.main.carouselDotsStyleCls +
        (oItem.main.buttons.length == 1 ? ' noIndicators' : '')
      "
      :style="{
        paddingTop: oItem.main.contentPaddingTop + 'px',
        paddingBottom: oItem.main.contentPaddingBottom + 'px',
        paddingLeft: oItem.main.contentPaddingLR + 'px',
        paddingRight: oItem.main.contentPaddingLR + 'px',
      }"
    >
      <el-carousel
        trigger="click"
        :indicator-position="oItem.main.indicatorPosition"
        :height="
          oItem.main.linesPerPage * (oItem.main.linesPerPage > 1 ? 80 : 85) +
          (oItem.main.buttons.length > 1 ? 10 : 0) +
          'px'
        "
        arrow="never"
        :interval="oItem.main.interval * 1000"
        :type="oItem.main.type"
        :direction="oItem.main.direction"
        :autoplay="oItem.main.autoplay"
        :loop="oItem.main.loop"
        :indicatorsActiveColor="oItem.main.carouselDotsHighLightColor||'transparent'"
        :style="{
          borderTopLeftRadius: oItem.main.contentBorderRadiusTop + 'px',
          borderTopRightRadius: oItem.main.contentBorderRadiusTop + 'px',
          borderBottomRightRadius: oItem.main.contentBorderRadiusBottom + 'px',
          borderBottomLeftRadius: oItem.main.contentBorderRadiusBottom + 'px',
          backgroundColor: oItem.main.buttonBgColor,
        }"
      >
        <el-carousel-item v-for="cl in oItem.main.buttons" :key="cl.id">
          <div class="page">
            <p
              class="button"
              v-for="(b, bIndex) in cl"
              :key="bIndex"
              :style="{ width: parseInt(100 / oItem.main.numberOfLines) + '%' }"
            >
              <img
                v-if="
                  (b.imgUrl && b.imgUrl.indexOf('icon-') == -1) &&
                  (b.default && b.imgUrl.indexOf('icon-') == -1)
                "
                :src="b.imgUrl || b.default"
                :style="{
                  borderRadius: oItem.main.buttonShape == 1 ? '100%' : '4px',
                }"
              />
              <i
                v-if="b.imgUrl && b.imgUrl.indexOf('icon-') > -1"
                :class="b.imgUrl"
                style="
                  width: 100%;
                  display: flex;
                  justify-content: center;
                  width: 44px;
                  align-items: center;
                  height: 44px;
                  font-size: 28px;
                "
                :style="{color: oItem.main.buttonIconColor}"
              ></i>
              <span :style="{ color: oItem.main.buttonFontColor||'transparent' }">{{
                b.name
              }}</span>
            </p>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>
  </div>
</template>
<script>
import buttonIcon from "../../../../assets/images/decorate/buttonIcon.png";
import Bus from "@/utils/bus";
import { mapState } from "vuex";
export default {
  name: "buttonGroupComponent",
  data() {
    return {
      buttonIcon,
      oItem: null,
    };
  },
  props: ["item", "ename", "id"],
  // import引入的组件, 需要注入到对象中才能使用
  components: {},
  // 生命周期 - 创建完成, 可以访问当前this实例
  created() {},
  // 生命周期 - 挂载完成, 可以访问DOM元素
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
    const emitName = this.ename + this.id;
    Bus.$off(emitName);
    Bus.$on(emitName, (control) => {
      //console.log("buttonGroupComponent被通知更新");
      this.oItem = null;
      this.$nextTick(() => {
        this.oItem = JSON.parse(control);
        this.setButtons();
      });
    });
  },
  //方法集合
  methods: {
    //页面初始化
    init() {
      this.oItem = null;
      this.$nextTick(() => {
        this.oItem = JSON.parse(JSON.stringify(this.item));
        this.setButtons();
      });
      
    },
    //根据每页展示行数，和每行展示按钮数，以及目前的按钮数，重新排列按钮展示方式
    setButtons() {
      let oItem = this.oItem;
      const buttons = JSON.parse(JSON.stringify(oItem.main.buttons));
      // console.log("按钮数",buttons.length);
      let arr = new Array();
      //每页展示行数
      const lines = oItem.main.linesPerPage;
      //每行展示按钮数
      const num = oItem.main.numberOfLines;
      // //console.log("每行展示按钮数 ",num);
      //每页展示的按钮数
      const total = lines * num;
      //当前拥有的按钮数
      let btns = 0;
      let realButtons = [];
      if (buttons[0] && buttons[0].id) {
        realButtons = buttons;
      } else if (buttons[0][0] && buttons[0][0].id) {
        realButtons = buttons[0];
      }
      btns = realButtons.length;
      //先不管每页展示几行，每行展示几个按钮，判断若当前按钮总数在1页内就能展示完
      let less = false; //是否涉及增减按钮
      if (btns < total) {
        less = true;
        let btnsArr = [];

        for (let i = 0; i < total - btns; i++) {
          btnsArr.push({
            id: "vlonButtonGroupItemId_" + new Date().getTime(),
            imgUrl: this.buttonIcon,
            name: "按钮文字",
            default: this.buttonIcon,
            linkUrl: "",
            linkName: "",
          });
        }
        arr = [];
        let ar = realButtons.concat(btnsArr);
        arr = [ar];

        //right中也需要增加
        let btnIndex = 0;
        oItem.right[1].catalog.forEach((item, idx) => {
          if (item.controlName === "buttonGroupComponent") {
            btnIndex = idx;
          }
        });
        oItem.right[1].catalog[btnIndex].list = JSON.parse(JSON.stringify(ar));
      } else if (btns == total) {
        arr = [];
        arr = [realButtons];
      } else {
        /*以下是分页功能，基于20220323新需求，默认每页固定只展示1行按钮，且1行最多只支持5个按钮，因此分页暂时弃用
        //若当前按钮数在1页内展示不完，则需要分页展示
        //页数
        let pages = 1;
        if(btns % total == 0) {
          pages = btns / total
        } else {
          pages = parseInt(btns / total) + 1;
        }
        let start = 0;
        for(let p=0; p<pages; p++) {
          let ar = new Array();
          let b=0;
          for(; start<btns; start++) {
            if(b == total) {
              break;
            }
            ar.push(buttons[start]);
            b++;
          }
          arr.push(ar)
        }
        */
        //以下是基于20220323新功能对按钮数进行调整
        //若当前的按钮数多余当前页、当前行能展示的数量，则直接从后面减去
        let btnsArr = [];
        for (let i = 0; i < total; i++) {
          btnsArr.push(realButtons[i]);
        }
        arr = [];
        arr.push(btnsArr);
        less = true;

        //right中也需要减去
        let btnIndex = 0;

        oItem.right[1].catalog.forEach((item, idx) => {
          if (item.controlName === "buttonGroupComponent") {
            btnIndex = idx;
          }
        });
        oItem.right[1].catalog[btnIndex].list = JSON.parse(
          JSON.stringify(btnsArr)
        );
      }
      oItem.main.buttons = JSON.parse(JSON.stringify(arr));
      // this.oItem = JSON.parse(JSON.stringify(oItem));
      // if (less) {
      //   let controls = this.decorate.controls;
      //   controls[this.controlsIndex] = JSON.parse(JSON.stringify(this.oItem));
      //   this.$store.dispatch("controls", controls);
      //   Bus.$emit(`updateRightChild${this.id}`, {
      //     controlsIndex: this.controlsIndex,
      //   });
      // }
    },
  },
  // 监听属性, 类似于data概念
  computed: mapState(["decorate"]),
  // 监听data中的数据变化
  watch: {},
  //如果页面有keep-alive缓存功能, 这个函数会触发
  activated() {},
  // 生命周期 - 销毁之前
  beforeDestroy() {},
  // 生命周期 - 销毁完成
  destroyed() {},
};
</script>
<style scoped lang="scss">
.buttonGroupComponent {
  .buttonSwiper {
    .el-carousel {
      background-color: #fff;
      background-position: center center;
      background-repeat: no-repeat;
      background-size: 100% 100%;
      background-attachment: scroll;
      .el-carousel__container {
        .el-carousel-item {
          .page {
            .button {
              img {
                overflow: hidden;
                transition: all 0.3s;
              }
              span {
              }
            }
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.buttonGroupComponent {
  .buttonSwiper {
    .el-carousel {
      overflow-y: hidden;
      .el-carousel__container {
        .el-carousel__item {
          box-sizing: border-box;
          .page {
            width: 100%;
            display: flex;
            flex-wrap: wrap;
            .button {
              height: 65px;
              margin-top: 10px;
              display: flex;
              flex-direction: column;
              align-items: center;
              img {
                width: 44px;
                height: 44px;
                transition: all 0.3s;
                display: block;
                overflow: hidden;
                margin-bottom: 5px;
              }
              span {
                font-size: 12px;
                width: 100%;
                display: flex;
                justify-content: center;
              }
            }
          }
        }
      }
      .el-carousel__indicators {
        .el-carousel__indicator {
          padding: 7px 5px;
          .el-carousel__button {
            height: 3px;
            width: 12px;
            border-radius: 20px;
          }
        }
      }
    }
    &.noIndicators {
      .el-carousel__indicators {
        display: none;
      }
    }
  }
}
</style>
